<template>
  <div class="channel-edit">
    <!-- 我的频道 -->
    <div>
      <div>
        <span>我的频道</span>
        <van-button
          style="float: right"
          size="mini"
          type="danger"
          plain
          @click="show"
          >{{ editInfo }}</van-button
        >
      </div>
      <van-grid>
        <van-grid-item
          class="mineChannel"
          v-for="(item, index) in ownChannels"
          :key="item.cid"
        >
          <span
            :class="{ active: value == index }"
            @click="changeActive(index)"
            >{{ item.cname }}</span
          >
          <van-icon
            name="cross"
            size="12"
            v-show="isShow && item.name != '推荐'"
            @click="del(index)"
          />
        </van-grid-item>
      </van-grid>
    </div>

    <!-- 可选频道 -->
    <div style="margin-top:20px">
      <div>
        <span>可选频道</span>
      </div>
      <van-grid>
        <van-grid-item
          v-for="item in optChannels"
          :key="item.cid"
          :text="item.cname"
          @click="add(item)"
        />
      </van-grid>
    </div>
  </div>
</template>

<script>
import { setChannelsAPI } from '@/api'
import { setChannel } from '@/utils/storage'
export default {
  data () {
    return {
      isShow: false,
      editInfo: '编辑'
    }
  },
  props: {
    ownChannels: {
      type: Array,
      required: true
    },
    allChannels: {
      type: Array,
      required: true
    },
    value: {
      trpe: Number,
      required: true
    }
  },
  methods: {
    del (index) {
      this.ownChannels.splice(index, 1)
      // 判断要删除的频道的下标是否小于当前高亮的下标，如果是，通知父组件盒子的高亮向后移
      if (index < this.value) {
        this.$emit('input', this.value - 1)
      }
      this.save()
    },
    show () {
      this.isShow = !this.isShow
      if (this.isShow == false) {
        this.editInfo = '编辑'
      } else {
        this.editInfo = '取消'
      }
    },
    changeActive (index) {
      this.$emit('input', index)
      this.$emit('close')
    },
    add (item) {
      this.ownChannels.push(item)
      this.save()
    },
    async save () {
      // 判断是否登录
      if (this.$store.state.tokenObj.token) {
        // 登录了，直接发请求
        // 先把我的频道改为接口需要的数据格式
        const channels = this.ownChannels.map((v, i) => {
          return {
            id: v.id,
            seq: i
          }
        })
        await setChannelsAPI({ channels })
      } else {
        // 没登录，存到本地
        setChannel(this.ownChannels)
      }
    }
  },
  computed: {
    optChannels () {
      return this.allChannels.filter(v => {
        // 结果为true,说明我的频道与可选频道都拥有这个频道,那么就舍去
        return !this.ownChannels.find(val => val.id === v.id)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.channel-edit {
  padding: 0 20px;
  .mineChannel {
    span {
      font-size: 14px;
    }
    .van-icon {
      position: absolute;
      right: 2px;
      top: 2px;
    }
  }
}
.active {
  color: red;
}
</style>
